const jwt = require('jsonwebtoken')
const {USER_DOES_NOT_EXISIS,NAME_OR_PASSWORD_IS_NOT_REQUIRED,PASSWORD_ERROR,UNAUTHORRIZATION,UNPERMISSION} = require("../contants/error-types")
const service = require("../service/user.service");
const authService = require("../service/auth.service")
const {md5password} = require("../utils/password-handle");
const {PUBLIC_KEY} = require("../app/config")

// 登录
const verifyLogin = async (ctx,next) => {
  //获取用户名和密码
  const {name,password} = ctx.request.body;

  //2.判断用户名和密码是否为空
  if(!name || !password){
    const error = new Error(NAME_OR_PASSWORD_IS_NOT_REQUIRED);
    return ctx.app.emit('error',error,ctx)
  }

  //3.判断用户名是否存在
  const result = await service.getUserByName(name);

  const user = result[0]

  if(!user){
    const error = new Error(USER_DOES_NOT_EXISIS)
    return ctx.app.emit('error',error,ctx)
  }

  //4.判断密码是否和数据库的密码是一致的
  if(md5password(password) !== user.password){
    const error = new Error(PASSWORD_ERROR)
    return ctx.app.emit('error',error,ctx)
  }

  ctx.user = user;

  await next()
}


//验证授权
const verifyAuth = async (ctx,next) => {
  console.log("验证授权的middleware~");

  //1.获取token
  const authorrization = ctx.headers.authorization;
  if(!authorrization){
    const error = new Error(UNAUTHORRIZATION)
    return ctx.app.emit('error',error,ctx)
  }
  const token = authorrization.replace('Bearer ','')
  

  //2.验证token
  try {
    const result = jwt.verify(token,PUBLIC_KEY,{
      algorithms:['RS256']
    })
    ctx.user = result
    console.log("user",ctx.user);
    await next()
  } catch (err) {
    console.log("err",err);
    const error = new Error(UNAUTHORRIZATION)
    ctx.app.emit('error',error,ctx)
  }
}

//查看用户是否有这个权限
const verifyPermission = (tableName) => {
  return async (ctx,next) =>  {
    console.log("验证权限的middleware");
  
    //1.获取参数
    const id = ctx.request.params[`${tableName}Id`];
    const {id:userId} = ctx.user
  
    console.log(tableName,id,userId);
    //2.查询是否具备权限
    try {
      const isPermission = await authService.checkPermission(tableName,id,userId)
      if(!isPermission.length) throw new Error()
      await next()
    } catch (err) {
      console.log(err);
      const error = new Error(UNPERMISSION)
      return ctx.app.emit("error",error,ctx)
    }
  }
}

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission
}